package com.wcgksoft.controller.att_management;

import com.wcgksoft.common.util.FileUpload;
import com.wcgksoft.common.util.Layui;
import com.wcgksoft.common.util.comm.StringUtils;
import com.wcgksoft.entity.Att_management.Att_management;
import com.wcgksoft.entity.Att_management.CheckWork_Month;
import com.wcgksoft.entity.Att_management.Healthy;
import com.wcgksoft.entity.Att_management.Healthy_statistics;
import com.wcgksoft.entity.ConstructionTeam.ConstructionTeam;
import com.wcgksoft.entity.Equipment.Equipment;
import com.wcgksoft.entity.system.SysUser;
import com.wcgksoft.service.Att_management.Att_managementService;
import com.wcgksoft.service.Att_management.CheckWork_MonthService;
import com.wcgksoft.service.Att_management.Healthy_statisticsService;
import com.wcgksoft.service.ConstructionTeam.ConstructionTeamService;
import com.wcgksoft.service.system.UserService;
import net.sf.json.JSONObject;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 周权
 * @Date: 2020/03/10/16:40
 * @Description:考勤系统
 */
@Controller
@RequestMapping(value = "system/att_management")
public class Att_managementController {
    @Autowired
    private Att_managementService att_managementService;
    @Autowired
    private ConstructionTeamService constructionTeamService;
    @Autowired
    private CheckWork_MonthService checkWork_monthService;
    @Autowired
    private Healthy_statisticsService healthy_statisticsService;

    /*
    * @Author: 周权
    * @Description:进入考勤系统默认查找该施工队
    * @Param:
    * @create: 2020/3/10 16:42
    * @return:
    */
    @ResponseBody
    @RequestMapping(value = "findTeam")
    public Layui findMember(@RequestParam(value = "a_tid", required = false) Integer a_tid,
                            @RequestParam(value = "role_id") Integer role_id) {
        if(role_id==2){
            return Layui.data(1, "查询成功",0, null);
        }else if(role_id==3){
            return Layui.data(1, "查询成功",0, null);
        }else if(role_id==4){
            ConstructionTeam byId = constructionTeamService.findById(a_tid);
            if(null!=byId){
                return Layui.data(0, "查询成功", byId);
            }
        }
        return Layui.data(1, "查询成功",0, null);
    }


    /*
    * @Author: 周权
    * @Description:考勤系统列表页面layui的table加载数据
    * @Param:
    * @create: 2020/3/11 10:29
    * @return:
    */
    @ResponseBody
    @RequestMapping(value = "findAll")
    public Layui findAll(@RequestParam(value = "a_tid", required = false) Integer a_tid,
                         @RequestParam(value = "e_id", required = false) Integer e_id,
                         @RequestParam(value = "role_id", required = false) Integer role_id,
                         @RequestParam(value = "area_id", required = false) Integer area_id,
                         @RequestParam(value = "page", required = false) Integer page,
                         @RequestParam(value = "limit", required = false) Integer limit,
                         @RequestParam(value = "starttime", required = false) String starttime,
                         @RequestParam(value = "endtime", required = false) String endtime,
                         @RequestParam(value = "a_name", required = false) String a_name) throws ParseException {
        DetachedCriteria criteria = DetachedCriteria.forClass(Att_management.class);
        if (null!=a_name&&!"".equals(a_name)) {
            criteria.add(Restrictions.eq("a_name", a_name));
        }
        if ((null!=starttime&&!"".equals(starttime)) && (null!=endtime&&!"".equals(endtime))) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parse = sdf.parse(starttime+" 00:00:00");
            Date parse2 = sdf.parse(endtime+" 23:59:99");
            criteria.add(Restrictions.between("a_createDate", parse, parse2));
        }
        if ((null!=starttime&&!"".equals(starttime)) && (null==endtime||"".equals(endtime))){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parse = sdf.parse(starttime+" 00:00:00");
            Date parse2 = sdf.parse("2099-12-01 23:59:99");
            criteria.add(Restrictions.between("a_createDate", parse, parse2));
        }
        if ((null!=endtime&&!"".equals(endtime)) && (null==starttime||"".equals(starttime))){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parse = sdf.parse(endtime+" 23:59:99");
            Date parse2 = sdf.parse("1997-12-01 00:00:00");
            criteria.add(Restrictions.between("a_createDate", parse2, parse));
        }
        if(role_id==2){
            criteria.add(Restrictions.eq("a_eid", e_id));
        } else if(role_id==3){
            criteria.add(Restrictions.eq("a_eid", e_id));
            criteria.add(Restrictions.eq("a_area_id", area_id));
        }else if(role_id==4){
            criteria.add(Restrictions.eq("a_tid", a_tid));
        }
        criteria.addOrder(Order.asc("a_createDate"));
        criteria.add(Restrictions.eq("a_status", 0));
        List<Att_management> byConditions = att_managementService.findByConditions(criteria,page,limit);
        return Layui.data(0, "查询成功", att_managementService.getTotalCount(), byConditions);
    }

    /*
    * @Author: 周权
    * @Description: 考勤系统列表页面的添加/修改考勤
    * @Param:
    * @create: 2020/3/11 10:38
    * @return:
    */
    @ResponseBody
    @RequestMapping(value = "update")
    public Layui update(HttpServletRequest request,
                        @RequestParam(value = "data", required = false) String data,
                        @RequestParam(value = "file",required = false) MultipartFile file,
                        @RequestParam(value = "file1",required = false) MultipartFile file1) throws ParseException {
        JSONObject param = JSONObject.fromObject(data);
        if (param == null) {
            return Layui.data(1, "请求格式有误", 0, null);
        } else {
            String id1 = String.valueOf(param.get("id"));
            if(null==id1||id1.equals("")){
                Att_management att_management = (Att_management) JSONObject.toBean(JSONObject.fromObject(data), Att_management.class);
                if (null != file) {
                    String image = FileUpload.picvideoupload("upload/picture", "file", request);
                    att_management.setA_am_picture("upload/picture/" + image);
                }
                if (null != file1) {
                    String image1 = FileUpload.picvideoupload("upload/picture", "file1", request);
                    att_management.setA_pm_picture("upload/picture/" + image1);
                }
                att_management.setA_status(0);
                att_management.setA_am_createDate(new Date());
                att_managementService.save(att_management);

                String a_tid = String.valueOf(param.get("a_tid"));//获得考勤所属队伍ID
                int tid = Integer.parseInt(a_tid);//字符串转数字
                Date a_createDate = att_management.getA_createDate();//获得此次签到日期
                Calendar cal = Calendar.getInstance();//建立日历
                cal.setTime(a_createDate);//日历设置时间
                int year = cal.get(Calendar.YEAR);//获得年
                String years = String.valueOf(year);//转字符串（年）
                DetachedCriteria criteria = DetachedCriteria.forClass(CheckWork_Month.class);
                criteria.add(Restrictions.eq("c_tid", tid));
                criteria.add(Restrictions.sqlRestriction("DATE_FORMAT(C_createDate,'%Y')= '" + years + "'"));//查询数据库字段为此次签到年份的数据
                List<CheckWork_Month> byConditions = checkWork_monthService.findByConditions(criteria);
                if(byConditions.size()==0){//平均人数表中没有当前队伍签到当年的数据
                    for(int i =1;i<=12;i++){//循环12次建立12张属于此施工队伍的月平均人数表
                        String mon;
                        if(i<10){
                            mon = years+"-0"+i;
                        }else{
                            mon = years+"-"+i;
                        }
                        String lastDayOfMonth = getLastDayOfMonth(mon);//获得当月最后天数 格式xxxx-xx-xx
                        Calendar cals = Calendar.getInstance();//新建日历类
                        SimpleDateFormat dateFormats = new SimpleDateFormat("yyyy-MM-dd");//格式化年-月-日
                        Date parses = dateFormats.parse(lastDayOfMonth);//转日期类
                        cals.setTime(parses);//日历设置获得时间
                        int month = cals.get(Calendar.DAY_OF_MONTH);//获得日（此数为调用getLastDayOfMonth方法所得到的当月最后一天）
                        CheckWork_Month checkWork_month = new CheckWork_Month();
                        checkWork_month.setC_area_id(att_management.getA_area_id());
                        checkWork_month.setC_eid(att_management.getA_eid());
                        checkWork_month.setC_project_id(att_management.getA_project_id());
                        checkWork_month.setC_tid(att_management.getA_tid());
                        checkWork_month.setC_name(att_management.getA_name());
                        checkWork_month.setC_ave(0.0);
                        checkWork_month.setC_mon(mon);
                        checkWork_month.setC_sum(0);
                        checkWork_month.setC_days(month);
                        checkWork_month.setC_createDate(new Date());
                        checkWork_monthService.save(checkWork_month);
                    }
                }

                String a_createDate1 = String.valueOf(param.get("a_createDate"));//添加考勤时 查找考勤当日
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date parse = sdf.parse(a_createDate1+" 00:00:00");
                Date parse2 = sdf.parse(a_createDate1+" 23:59:99");
                String a_tid1 = String.valueOf(param.get("a_tid"));
                int a_tid2 = Integer.parseInt(a_tid1);
                DetachedCriteria criteria2 = DetachedCriteria.forClass(Healthy_statistics.class);//查询健康月平均日表是否已创建
                criteria2.add(Restrictions.between("s_createDate", parse, parse2));
                criteria2.add(Restrictions.eq("s_tid", a_tid2));
                List<Healthy_statistics> byConditions3 = healthy_statisticsService.findByConditions(criteria2);
                if(byConditions3.size()>0){//已创建健康月平均日表  （如果没创建健康表说明是先添加的考勤 健康表会在添加健康时创建统计表）
                    for(int k = 0;k<byConditions3.size();k++){
                        byConditions3.get(0).setAtt_management(att_management);//获得第一个（理论上一个队伍一天只有一张统计表）
                        healthy_statisticsService.saveMerge(byConditions3.get(0));//有健康表 在添加考勤时将考勤表关联到健康表（先录入健康后录入考勤的情况） 以便在健康表中得到考勤表中的实到人数
                        break;
                    }
                }
                return Layui.data(0, "添加成功", 1, Layui.addList(att_management));
            }else{
                Att_management att_management = (Att_management) JSONObject.toBean(JSONObject.fromObject(data), Att_management.class);
                if (null != file) {
                    String image = FileUpload.picvideoupload("upload/picture", "file", request);
                    att_management.setA_am_picture("upload/picture/" + image);
                    att_management.setA_am_createDate(new Date());
                }
                if (null != file1) {
                    String image1 = FileUpload.picvideoupload("upload/picture", "file1", request);
                    att_management.setA_pm_picture("upload/picture/" + image1);
                    att_management.setA_pm_createDate(new Date());
                }
                String id = String.valueOf(param.get("id"));
                int i1 = Integer.parseInt(id);
                Att_management byId = att_managementService.findById(i1);
                Integer a_pm_num = byId.getA_pm_num();//根据id找到到条签到数据下午出勤人数（在下边判断下午出勤数是否为空）

                String pmnum = String.valueOf(param.get("a_pm_num"));
                int pm = Integer.parseInt(pmnum);//获取下午出勤数
                String should = String.valueOf(param.get("a_should_num"));//获取应到人数
                int shouldnum = Integer.parseInt(should);
                int absnum = shouldnum-pm;//缺勤人数=应到人数-下午出勤人数
                if(shouldnum>pm){
                    att_management.setA_absence(1);//应到人数>出勤人数 缺勤

                }else if(shouldnum==pm){
                    att_management.setA_absence(0);//应到人数=出勤人数 满勤
                }
                att_management.setA_abs_num(absnum);
                att_management.setA_status(0);
                Integer a_am_num = byId.getA_am_num();//获得上午签到人数
                String a_am_num1 = String.valueOf(param.get("a_am_num"));
                int a_am_num2 = Integer.parseInt(a_am_num1);//获得修改后的上午人数
                if(a_am_num!=a_am_num2){//如果不相等，证明已修改上午人数 上午签到时间重新设置
                    att_management.setA_am_createDate(new Date());
                }
                if(null!=byId.getA_pm_createDate()){//下午签到时间不为空，证明下午已签到（修改下午人数可能）
                    Integer a_pm_num1 = byId.getA_pm_num();//获得之前下午签到人数
                    if(a_pm_num1!=pm){//证明已修改下午人数
                        att_management.setA_pm_createDate(new Date());
                    }
                }else{
                    att_management.setA_pm_createDate(new Date());//下午签到时间为空 第一次下午签到 设置签到时间
                }
                String a_createDates = String.valueOf(param.get("a_createDate"));
                SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date parse1 = sdfs.parse(a_createDates+" 10:00:00");
                att_management.setA_createDate(parse1);
                att_managementService.saveOrUpdate(att_management);

                String a_tid = String.valueOf(param.get("a_tid"));//获得考勤所属队伍ID
                int tid = Integer.parseInt(a_tid);//字符串转数字
                Date a_createDate = att_management.getA_createDate();//获得此次签到日期
                Calendar cal = Calendar.getInstance();//建立日历
                cal.setTime(a_createDate);//日历设置时间
                int year = cal.get(Calendar.YEAR);//获得年
                String years = String.valueOf(year);//转字符串（年）
                int mons = cal.get(Calendar.MONTH)+1;
                DetachedCriteria criteria = DetachedCriteria.forClass(CheckWork_Month.class);
                criteria.add(Restrictions.eq("c_tid", tid));
                criteria.add(Restrictions.sqlRestriction("DATE_FORMAT(C_createDate,'%Y')= '" + years + "'"));//查询数据库字段为此次签到年份的数据
                List<CheckWork_Month> byConditions = checkWork_monthService.findByConditions(criteria);
                String s1;
                if(mons<10){
                    s1 = "0"+String.valueOf(mons);//如果月份小于10月 字符串前加0
                }else{
                    s1 = String.valueOf(mons);
                }
                String yramon = years+"-"+s1;//拼接字符串 xxxx-0x || xxxx=xx
                for(CheckWork_Month checkWork_month:byConditions){
                    String c_mon = checkWork_month.getC_mon();//循环人数平均值表
                    if(yramon.equals(c_mon)){//找到与签到年月相同的那条数据
                        Integer sum;
                        if(null==a_pm_num) {//表中下午出勤人数没有值（第一次下午签到）
                            sum = checkWork_month.getC_sum() + att_management.getA_pm_num();//月总签到=总签到值+新增签到值
                            checkWork_month.setC_sum(sum);
                        }else{//表中下午出勤人数有值（修改下午签到）
                            sum = checkWork_month.getC_sum() + pm-a_pm_num;//月总签到=总签到值+修改后数据-修改前数据
                            checkWork_month.setC_sum(sum);
                        }
                        double v = checkWork_month.getC_days().doubleValue();
                        double l = sum / v;//考勤人数/当月天数==月平均人数值
                        l = (double) Math.round(l * 100) / 100;//保留小数点后两位
                        checkWork_month.setC_ave(l);
                        checkWork_monthService.saveMerge(checkWork_month);
                    }
                }

                String a_createDate1 = String.valueOf(param.get("a_createDate"));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date parse = sdf.parse(a_createDate1+" 00:00:00");
                Date parse2 = sdf.parse(a_createDate1+" 23:59:99");
                String a_tid1 = String.valueOf(param.get("a_tid"));
                int a_tid2 = Integer.parseInt(a_tid1);
                DetachedCriteria criteria2 = DetachedCriteria.forClass(Healthy_statistics.class);
                criteria2.add(Restrictions.between("s_createDate", parse, parse2));
                criteria2.add(Restrictions.eq("s_tid", a_tid2));
                List<Healthy_statistics> byConditions3 = healthy_statisticsService.findByConditions(criteria2);
                if(byConditions3.size()>0){//已创建健康表
                    for(int k = 0;k<byConditions3.size();k++){
                        byConditions3.get(0).setS_teamnum(att_management.getA_pm_num());//修改考勤表证明是下午考勤或修改考勤 将下午实到人数添加到健康表
                        healthy_statisticsService.saveMerge(byConditions3.get(0));
                        break;
                    }
                }
                return Layui.data(0, "修改成功", 1, Layui.addList(att_management));
            }
        }
    }

    /*
    * @Author: 周权
    * @Description:考勤系统删除考勤
    * @Param:
    * @create: 2020/3/11 10:46
    * @return:
    */
    @ResponseBody
    @RequestMapping(value = "delete")
    public Layui delete(@RequestParam(value = "id") Integer id) {
        Att_management byId = att_managementService.findById(id);
        byId.setA_status(1);//设置考勤状态为1 在列表页隐藏
        att_managementService.saveOrUpdate(byId);
        return Layui.data(1, "删除成功", 1, null);
    }

    /*
     * @Author: 周权
     * @Description:获得当前月份天数
     * @Param:
     * @create: 2020/3/12 16:57
     * @return:
     */
    public static String getLastDayOfMonth(String yearMonth) {
        int year = Integer.parseInt(yearMonth.split("-")[0]);  //年
        int month = Integer.parseInt(yearMonth.split("-")[1]); //月
        Calendar cal = Calendar.getInstance();
        // 设置年份
        cal.set(Calendar.YEAR, year);
        // 设置月份
        // cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.MONTH, month); //设置当前月的上一个月
        // 获取某月最大天数
        //int lastDay = cal.getActualMaximum(Calendar.DATE);
        int lastDay = cal.getMinimum(Calendar.DATE); //获取月份中的最小值，即第一天
        // 设置日历中月份的最大天数
        //cal.set(Calendar.DAY_OF_MONTH, lastDay);
        cal.set(Calendar.DAY_OF_MONTH, lastDay - 1); //上月的第一天减去1就是当月的最后一天
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    /*
    * @Author: 周权
    * @Description: 查找当日当前施工队伍是否点击出勤
    * @Param:
    * @create: 2020/3/30 11:16
    * @return:
    */
    @ResponseBody
    @RequestMapping(value = "findatt_manage")
    public Integer findHealthy(@RequestParam(value = "a_tid") Integer a_tid) throws ParseException {
        DetachedCriteria criteria = DetachedCriteria.forClass(Att_management.class);
        criteria.add(Restrictions.eq("a_tid", a_tid));

        Date date = new Date();
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        int i = instance.get(Calendar.YEAR);
        int i1 = instance.get(Calendar.MONTH)+1;
        int i2 = instance.get(Calendar.DAY_OF_MONTH);
        String s = String.valueOf(i);
        String s1;
        if(i1<10){
            s1 = "0"+String.valueOf(i1);
        }else{
            s1 = String.valueOf(i1);
        }
        String s2;
        if(i2<10){
            s2 = "0"+String.valueOf(i2);
        }else{
            s2 = String.valueOf(i2);
        }
        String s3 = s+"-"+s1+"-"+s2+" 00:00:00";
        String s4 = s+"-"+s1+"-"+s2+" 23:59:99";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse1 = sdf.parse(s3);
        Date parse2 = sdf.parse(s4);
        criteria.add(Restrictions.between("a_createDate", parse1, parse2));
        List<Att_management> byConditions = att_managementService.findByConditions(criteria);
        if(byConditions.size()>0){
            return 0;
        }else{
            return 1;
        }
    }
}
